package com.lcredu.springbootusersys.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * @author 黎长容
 * @date 2025-08-17 19:33
 */
//@Configuration
public class DruidDataSourceConfig {
    /**
     * @param DruidDataSource
     * @return
     * @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
     * 如果容器没有DataSource就注入默认的
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource getDatasource(DruidDataSourceConfig DruidDataSource) throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        //添加sql监控和sql防火墙
        druidDataSource.setFilters("stat,wall");
        // 这里可以设置 Druid 数据源的各种属性
        return druidDataSource;
    }

    @Bean
    public ServletRegistrationBean statViewServlet() {
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> stat = new ServletRegistrationBean<>(statViewServlet);
        stat.addUrlMappings("/druid/*");
        stat.addInitParameter("loginUsername", "lcr");
        stat.addInitParameter("loginPassword", "123456");
        return stat;
    }

    //配置web监控
    @Bean
    public FilterRegistrationBean druidWebStatFilter() {
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<WebStatFilter> webStatFilterFilterRegistrationBean = new FilterRegistrationBean<>(webStatFilter);
        webStatFilterFilterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        webStatFilterFilterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return webStatFilterFilterRegistrationBean;
    }
}
